#pragma once
#include <ChakraCore.h>
#include <string>
#include <cassert>
#include <memory>
#include "tools.h"

class ChakraErrorException
{
private:
	JsErrorCode _errorCode;
public:
	ChakraErrorException(JsErrorCode errorCode) : _errorCode(errorCode) {}
	JsErrorCode GetErrorCode() const { return _errorCode; }
};

void  CheckThrow(JsErrorCode errorCode);

JsValueRef  Vconvert(std::wstring var);

JsValueRef  Vconvert(int var);

class CCJs
{
public:
	CCJs() {
		CheckThrow(JsCreateRuntime(JsRuntimeAttributeNone, nullptr, &_runtime));
		CheckThrow(JsCreateContext(_runtime, &_context));
		CheckThrow(JsSetCurrentContext(_context));
		CheckThrow(JsGetGlobalObject(&_globalObject));
	};
	~CCJs() {
		CheckThrow(JsSetCurrentContext(JS_INVALID_REFERENCE));
		CheckThrow(JsDisposeRuntime(_runtime));
	};
	void RunScript(_In_z_ const wchar_t* script);
	JsValueRef GetObjectAsProperty(_In_z_ const wchar_t* funcname);
	JsContextRef GetContext();
	JsContextRef GetGlobal();
private:
	JsRuntimeHandle _runtime;
	JsContextRef _context;
	JsValueRef _globalObject;
	unsigned int _currentSourceContext = 0;
};


std::wstring LoadFile(const wchar_t* n);

JsValueRef  Vconvert(int var);

JsValueRef  Vconvert(std::wstring var);

JsValueRef  Vconvert(std::string var);